FactoryBot 使用总结

1、四种创建方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 返回对象 但是不保存
user = build(:user)

# 返回对象并且保存
user = create(:user)

# 返回可用于构建用户实例的属性 HASH
attrs = attributes_for(:user)

# 返回一个对象,该对象的所有定义属性都已存根
stub = build_stubbed(:user)

# 将一个块传递给上面的任何方法都将产生返回对象
create(:user) do |user|
user.posts.create(attributes_for(:post))
end

2、覆盖属性

1
2
3
4
# Build a User instance and override the first_name property
user = build(:user, first_name: "Joe")
user.first_name
# => "Joe"

3、重命名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
factory :user, aliases: [:author, :commenter] do
first_name { "John" }
last_name { "Doe" }
date_of_birth { 18.years.ago }
end

factory :post do
author
# instead of
# association :author, factory: :user
title { "How to read a book effectively" }
body { "There are five steps involved." }
end

factory :comment do
commenter
# instead of
# association :commenter, factory: :user
body { "Great article!" }
end

4、属性依赖

1
2
3
4
5
6
7
8
factory :user do
first_name { "Joe" }
last_name { "Blow" }
email { "#{first_name}.#{last_name}@example.com".downcase }
end

create(:user, last_name: "Doe").email
# => "joe.doe@example.com"

5、通过嵌套工厂,您可以轻松地为同一个类创建多个工厂,而无需重复常见的属性:

1
2
3
4
5
6
7
8
9
10
11
factory :post do
title { "A title" }

factory :approved_post do
approved { true }
end
end

approved_post = create(:approved_post)
approved_post.title # => "A title"
approved_post.approved # => true
1
2
3
4
5
6
7
factory :post do
title { "A title" }
end

factory :approved_post, parent: :post do
approved { true }
end

6、在factory_bot 5中,关联默认使用与其父对象相同的构建策略:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
FactoryBot.define do
factory :author

factory :post do
author
end
end

post = build(:post)
post.new_record? # => true
post.author.new_record? # => true

post = create(:post)
post.new_record? # => false
post.author.new_record? # => false

last update time 2022-04-25